<?php

namespace Mobile\Controller;

/**
 * Description of UserController.class控制器实例
 * 
 * @author songanwei
 * @date 2016-1-22
 */
class UserController extends ParentController {

    protected function _initialize() {
        parent::_initialize();
        $this->validateUtil = new \Org\Util\Validate();
    }

    /**
     * @description 移动端登录
     * @modify songanwei 2016-01-22
     * @modify trainyao 2016-03-16 修改测试友好
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function login() {
        $params = I('post.');

        // v2.0.11的参数校验 支持国际号码校验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
            $validateRule = array(
                'password' => 'notnull,notempty',
            );

            $areaCode = I('post.areaCode', '86', 'string');
            $this->ajaxValidateReturn($this->validateUtil, $params['mobile'], 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        } else {
            $validateRule = array(
                'mobile' => 'notnull,notempty,mobile',
                'password' => 'notnull,notempty',
            );
        }
       
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            return;
        }

        $mobile = $params['mobile'];
        $areaCode = isset($areaCode) ? $areaCode : '86';
        $encryptPassword = $params['password'];

        //解密字符串
        $RSAEncryptor = new \Org\Util\RSAEncrypt();
        $decryptPassword = $RSAEncryptor->meizhuDecrypt($encryptPassword);
        if (!$decryptPassword) {
            returnJson(403, 101, 'error');
            return;
        }

        //获取用户密码
        $password = substr($decryptPassword, 8);
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $password, 'password');
        if (!$validateResult) {
            return;
        }

        //检查用户登录
        $adminLoginLogic = A('Common/AdminLogin', 'Logic');
        $adminLogin = $adminLoginLogic->login($mobile, hash('sha256', $password), true, $areaCode);
        if (empty($adminLogin)) {
            return;
        }

        //生成token
        $salt = date('YmdHis');
        $token = $RSAEncryptor->meizhuEncrypt($salt . $password);
        if (!$token) {
            returnJson(500, 505, 'error');
            return;
        }

        $adminLogin = $adminLoginLogic->getInfo($adminLogin['id']);
        //返回数据
        $data = array(
            'userId' => $adminLogin['id'],
            'token' => $token,
            'name' => $adminLogin['name'],
            'areaCode' => $adminLogin['areacode'],
            'mobile' => $adminLogin['mobile'],
            'headUrl' => formatUrl($adminLogin['headpath']),
            'role' => $adminLogin['role'],
        );
        returnJson(200, 200, $data);
    }

    /**
     * @description 更新设置新密码
     * @modify songanwei 2016-01-22
     * @modify trainyao 2016-03-16 修改测试友好
     */
    public function updatePassword() {
        $params = I('post.');
        $error = false;
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'password' => 'notnull,notempty',
            'newPassword' => 'notnull,notempty'
        );
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $params['userId'];
            $token = $params['token'];
            $encryptOldPassword = $params['password'];
            $encryptNewPassword = $params['newPassword'];

            //验证token
            $this->checkMobileToken($userId, $token);

            $RSAEncryptor = new \Org\Util\RSAEncrypt();
            $decryptOldPassword = $RSAEncryptor->meizhuDecrypt($encryptOldPassword);
            $decryptNewPassword = $RSAEncryptor->meizhuDecrypt($encryptNewPassword);

            //获取用户真实密码
            $oldPassword = substr($decryptOldPassword, 8);
            $newPassword = substr($decryptNewPassword, 8);
            $validateResult = $this->ajaxValidateReturn($this->validateUtil, $newPassword, 'password');
            if (!$validateResult) {
                $error = true;
            }

            if (!$error) {
                //检查原密码正确性
                $adminLoginLogic = A('Common/AdminLogin', 'Logic');
                $adminLogin = $adminLoginLogic->getInfo($userId);
                if ($adminLogin['password'] != hash("sha256", $oldPassword)) {
                    returnJson(403, 102);
                    $error = true;
                }

                //更新密码
                if (!$error) {
                    $adminLoginModel = D('AdminLogin');
                    $result = $adminLoginModel->setPassword($userId, hash("sha256", $newPassword));
                    if ($result == false) {
                        returnJson(500, 509);
                        $error = true;
                    }
                }

                //设置新的token数据
                if (!$error) {
                    $salt = date('YmdHis');
                    $token = $RSAEncryptor->meizhuEncrypt($salt . $newPassword);
                    if (!$token) {
                        returnJson(500, 505, 'error');
                        $error = true;
                    }
                    if (!$error) {
                        $data = array('token' => $token);
                        returnJson(200, 200, $data);
                    }
                }
            }
        }
    }

    /**
     * @description 原手机号获取短信验证码
     * @modify songanwei 2016-01-22
     */
    public function sendMobile() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);

        //
        $userId = $params['userId'];
        $token = $params['token'];
        $this->checkMobileToken($userId, $token);

        // 检测60秒防刷
        $mobileSendTime = session(C('SERCURE_MOBILE_VCODE_TIME')) ? session(C('SERCURE_MOBILE_VCODE_TIME')) : 0;
        $result = time() - $mobileSendTime - 60;


        //可再次发送短信验证码
        if ($result > 0) {
            $adminLoginModel = D('AdminLogin');
            $adminLogin = $adminLoginModel->getInfo($userId);
            $mobile = $adminLogin['mobile'];
            $areacode = $adminLogin['areacode'];
            $mobileVcode = getRandomNumber();

            // v2.0.11的参数校验 支持国际号码发送短信
            $version = getVersion(array('2.0.11'));
            if ($version >= '2.0.11') {
                if ($areacode == '86') {
                    $smsUtil = new \Org\Util\Sms();
                    $result = $smsUtil->sendVocode($mobile, $mobileVcode);
                } else {
                    $smsUtil = new \Org\Util\yunPian();
                    $result = $yunPian->sendVcode($areacode, $mobile, $mobileVcode);
                }
            } else {
                $smsUtil = new \Org\Util\Sms();
                $result = $smsUtil->sendVocode($mobile, $mobileVcode);
            }

            if (!$result) {
                returnJson(403, 151, 'error');
            }

            session_id($mobile);
            session_start();

            //session保存验证码
            session(C('SERCURE_MOBILE_VCODE'), $mobileVcode);
            //session保存验证码发送时间
            session(C('SERCURE_MOBILE_VCODE_TIME'), time());
            //session保存验证码有效结束时间
            session(C('SERCURE_MOBILE_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_VCODE_END_TIME_EFFECTIVE'));
            returnJson(200, 200, 'success');
        } else {
            returnJson(403, 107, 'error');
        }
    }

    /**
     * @description 验证原手机号短信
     * @modify songanwei 2016-01-22
     */
    public function verifyWithMobile() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'vcode' => 'notnull,notempty,vcode6'
        );
        $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        $mobileCode = $params['vcode'];
        $userId = $params['userId'];
        $token = $params['token'];
        $this->checkMobileToken($userId, $token);

        $adminLoginModel = D('AdminLogin');
        $adminLogin = $adminLoginModel->getInfo($userId);
        $mobile = $adminLogin['mobile'];

        session_id($mobile);
        session_start();

        //获取验证码结束时间
        $mobileVcodeEndTime = session(C('SERCURE_MOBILE_VCODE_END_TIME'));
        //获取验证码
        $mobileVcode = session(C('SERCURE_MOBILE_VCODE'));
        // 与session内的效验码以及过期时间进行比对
        if (($mobileVcode != $mobileCode) || ($mobileVcodeEndTime <= time())) {
            returnJson(403, 120);
        }
        session(C('SERCURE_MOBILE_VCODE'), null);
        session(C('SERCURE_MOBILE_VCODE_TIME'), null);
        session(C('SERCURE_MOBILE_VCODE_END_TIME'), null);
        returnJson(200, 200);
    }

    /**
     * @description 发送更换新手机号短信
     * @modify songanwei 2016-01-22
     * @modify trainyao 2016-03-16 代码测试友好
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function sendMobileNew() {
        $error = false;
        $params = I('post.');

        // v2.0.11增加国际手机检验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
             $validateRule = array(
                'userId' => 'notnull,notempty,id',
                'token' => 'notnull,notempty',
                'mobile' => 'notnull,notempty'
            );

            $areaCode = I('post.areaCode', '86', 'string');
            $this->ajaxValidateReturn($this->validateUtil, $params['mobile'], 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
        } else {
            $validateRule = array(
                'userId' => 'notnull,notempty,id',
                'token' => 'notnull,notempty',
                'mobile' => 'notnull,notempty,mobile'
            );
        }
        
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $params['userId'];
            $token = $params['token'];
            $mobile = $params['mobile'];

            $this->checkMobileToken($userId, $token);

            $adminLoginModel = D('AdminLogin');
            //检查手机号是否与之前手机号一样
            $adminLogin = $adminLoginModel->getInfo($userId);
            if ($adminLogin['mobile'] == $mobile) {
                returnJson(403, 106);
                $error = true;
            }

            if (!$error) {
                //检查手机号是否已被注册
                $areaCode = isset($areaCode) ? $areaCode : '86';
                $adminLogin = $adminLoginModel->getInfoByMobile($mobile, $areaCode);
                if ($adminLogin) {
                    returnJson(403, 105);
                    $error = true;
                }

                session_id($mobile);
                session_start();

                if (!$error) {
                    // 检测60秒防刷
                    $mobileSendTime = session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) ? session(C('SERCURE_MOBILE_NEW_VCODE_TIME')) : 0;
                    $result = time() - $mobileSendTime - 60;

                    //可再次发送短信验证码
                    if ($result > 0) {
                        $mobileVcode = getRandomNumber();

                        // v2.0.11国际手机发送短信
                        if ($version >= '2.0.11' && isset($areaCode)) {
                            //发送短信
                            if ($areaCode == '86') {
                                    $smsUtil = new \Org\Util\Sms();
                                    $result = $smsUtil->sendVocode($mobile, $mobileVcode);
                            } else {
                                    $yunPian = new \Org\Util\yunPian();
                                    $result = $yunPian->sendVcode($areaCode, $mobile, $mobileVcode);
                            }
                        } else {
                            $smsUtil = new \Org\Util\Sms();
                            $result = $smsUtil->sendVocode($mobile, $mobileVcode);
                        }
                        
                        if (!$result) {
                            returnJson(403, 151, 'error');
                            $error = true;
                        }

                        if (!$error) {
                            //保存新手机号
                            session(C('SERCURE_MOBILE_NEW'), $mobile);
                            //session保存验证码
                            session(C('SERCURE_MOBILE_NEW_VCODE'), $mobileVcode);
                            //session保存验证码发送时间
                            session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), time());
                            //session保存验证码有效结束时间
                            session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), time() + C('SERCURE_MOBILE_NEW_VCODE_END_TIME_EFFECTIVE'));
                            returnJson(200, 200, 'success');
                        }
                    } else {
                        returnJson(403, 107, 'error');
                    }
                }
            }
        }
    }

    /**
     * @description 验证并更换新手机号
     * @modify songanwei 2016-01-22
     * @modify trainyao 2016-03-16 代码测试友好
     * @modify wenhui 2017-05-04 增加国际手机检验
     */
    public function verifyWithMobileNew() {
        $error = false;
        $params = I('post.');

        // v2.0.11增加国际手机检验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
            $validateRule = array(
                'userId' => 'notnull,notempty,id',
                'token' => 'notnull,notempty',
                'vcode' => 'vcode6',
                'mobile' => 'notnull,notempty'
            );
            $areaCode = I('post.areaCode', '86', 'string');
            $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params['mobile'], 'globalMobile',
                    array('globalMobile' => array('function', 'checkGlobalMobile,' . $areaCode, '403,130,error'),
                ));
            if (!$validateResult) {
                $error = true;
            }
        } else {
            $validateRule = array(
                'userId' => 'notnull,notempty,id',
                'token' => 'notnull,notempty',
                'vcode' => 'vcode6',
                'mobile' => 'notnull,notempty,mobile'
            );
        }
        
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $params['userId'];
            $token = $params['token'];
            $vcode = $params['vcode'];
            $mobile = $params['mobile'];

            $this->checkMobileToken($userId, $token);

            session_id($mobile);
            session_start();

            //检查数据
            $mobileNew = session(C('SERCURE_MOBILE_NEW'));
            if (!$mobileNew) {
                returnJson(403, 120);
                $error = true;
            }

            if (!$error) {
                //获取验证码结束时间
                $mobileVcodeEndTime = session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'));
                //获取验证码
                $mobileVcode = session(C('SERCURE_MOBILE_NEW_VCODE'));
                //验证新的短信手机
                if (($mobileNew != $mobile) || ($vcode != $mobileVcode)) {
                    returnJson(403, 120);
                    $error = true;
                }
                if (($mobileVcodeEndTime <= time())) {
                    returnJson(403, 153);
                    $error = true;
                }

                if (!$error) {
                    $adminLoginModel = D('AdminLogin');
                    //更换手机号
                    if ($version >= '2.0.11' && isset($areaCode)) {
                        $result = $adminLoginModel->setMobile($userId, $mobileNew, $areaCode);
                    } else {
                        $result = $adminLoginModel->setMobile($userId, $mobileNew);
                    }

                    if ($result == false) {
                        returnJson(500, 509);
                        $error = true;
                    }

                    if (!$error) {
                        session(C('SERCURE_MOBILE_NEW_VCODE'), null);
                        session(C('SERCURE_MOBILE_NEW_VCODE_TIME'), null);
                        session(C('SERCURE_MOBILE_NEW_VCODE_END_TIME'), null);
                        returnJson(200, 200);
                    }
                }
            }
        }
    }

    /**
     * @description 更新名称
     * @modify songanwei 2016-01-25
     * @modify trainyao 2016-03-17 代码测试友好
     * @for v1.0.0  ios
     */
    public function updateName() {
        $error = false;
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'name' => 'notnull,notempty,nameLength20'
        );
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $params['userId'];
            $token = $params['token'];
            $name = $params['name'];

            $this->checkMobileToken($userId, $token);
            $adminLoginModel = D('AdminLogin');
            $result = $adminLoginModel->setName($userId, $name);
            if ($result == false) {
                returnJson(500, 509);
                $error = true;
            }
            if (!$error) {
                returnJson(200, 200);
            }
        }
    }

    /**
     * 获取用户信息
     * @modify trainyao 2016-02-17    创建
     * @for v1.0.0 ios
     */
    public function info() {
        $param = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty'
        );
        // v2.0.11增加国际手机检验
        $version = getVersion(array('2.0.11'));
        if ($version >= '2.0.11') {
            $validateRule['hotel'] = 'notnull,notempty,id';
        }
        $validatePass = $this->ajaxValidateReturn($this->validateUtil, $param, $validateRule);
        if (!$validatePass) {
            return;
        }

        $userId = $param['userId'];
        $token = $param['token'];
        $hotel = isset($param['hotel']) ? $param['hotel'] : null;
        $this->checkMobileToken($userId, $token);

        $adminLoginLogic = A('Common/AdminLogin', 'Logic');
        $adminLogin = $adminLoginLogic->getInfo($userId, $hotel);

        if (!empty($adminLogin)) {
            $returnData = array(
                'name' => $adminLogin['name'],
                'areaCode' => $adminLogin['areacode'],
                'mobile' => $adminLogin['mobile'],
                'headUrl' => formatUrl($adminLogin['headpath']),
                'role' => $adminLogin['role'],
            );
            returnJson(200, 200, $returnData);
        } else {
            returnJson(403, 100);
        }
    }

    /**
     * @description  获取身份证图片数据
     * @modify wenhui 2016-06-19
     */
    public function getIdInformation() {
        $params = I('post.');
        $validateRule = array(
            'userId' => 'notnull,notempty,id',
            'token' => 'notnull,notempty',
            'hotel' => 'notnull,notempty,id'
        );
        $validateResult = $this->ajaxValidateReturn($this->validateUtil, $params, $validateRule);
        if (!$validateResult) {
            $error = true;
        }

        if (!$error) {
            $userId = $params['userId'];
            $token = $params['token'];
            $this->checkMobileToken($userId, $token);
        }

        $config_info = C('identity');
        // 检测文件大小
        $fileSizes = array_column($_FILES, 'size');
        foreach ($fileSizes as $fileSize) {
            if ($fileSize > $config_info['maxSize']) {
                returnJson(403, 511);
                return;
            }
        }
        unset($fileSize);

        $config = array(
            'maxSize' => $config_info['maxSize'],
            'rootPath' => $config_info['rootPath'],
            'savePath' => $config_info['savePath'],
            'exts' => $config_info['exts'],
            'subName' => array('date', 'Ymd'),
        );

        $upload = new \Think\Upload($config);
        $info = $upload->upload();
        if (!$info) {
            returnJson(500, 511, $upload->getError());
            return;
        }
        if (isset($info['face'])) {
            $fileNameData['face'] = 'Uploads/' . $info['face']['savepath'] . $info['face']['savename'];  
        }
        if (isset($info['back'])) {
            $fileNameData['back'] = 'Uploads/' . $info['back']['savepath'] . $info['back']['savename'];  
        }

        if (!isset($fileNameData) || empty($fileNameData)) {
            returnJson(500, 511);
            return;
        }
        // 获取图片数据
        $jsonData = getIdDate($fileNameData);
        if ($jsonData == false) {
            returnJson(500, 511);
            return;
        }

        // 删除图片
        foreach ($fileNameData as $key => $fileName) {
            unlink($fileName);
        }

        // 组装数据
        $imageData = array();
        foreach ($jsonData['outputs'] as $key => $value) {
            $valueDate = json_decode($value['outputValue']['dataValue'], true);
            $config_str = json_decode($valueDate['config_str'], true);
            if ($config_str['side'] == 'face') {
                $imageData['name'] = $valueDate['name'];
                $imageData['sex'] = $valueDate['sex'];
                $imageData['nationality'] = $valueDate['nationality'];
                $imageData['num'] = $valueDate['num'];
                $imageData['address'] = $valueDate['address'];
            } else {
                $imageData['issue'] = $valueDate['issue'];
                $imageData['start_date'] = $valueDate['start_date'];
                $imageData['end_date'] = $valueDate['end_date'];
            }
        }

        if (empty($imageData) || empty($imageData['name'])) {
            returnJson(500, 511);
            return;
        }

        returnJson(200, 200, $imageData);
    }

}
